package com.tang.framework.component.security;

import com.alibaba.fastjson.JSON;
import com.tang.common.constant.HttpStatus;
import com.tang.common.constant.message.LocaleMessage;
import com.tang.common.utils.ServletUtil;
import com.tang.framework.core.domain.HttpResult;
import org.springframework.context.MessageSource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private MessageSource messageSource;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ServletUtil.renderString(response, JSON.toJSONString(
                HttpResult.error(HttpStatus.FORBIDDEN, messageSource
                        .getMessage(LocaleMessage.Base.ACCESS_DENIED, null, request.getLocale()))));
    }
}
